// 文章详情页面服务逻辑

import type { Article, Comment } from './types'

const API_BASE_URL = 'http://localhost:3000/api'

// 获取文章详情
export const fetchArticle = async (id: string): Promise<Article> => {
  const token = localStorage.getItem('token')
  const res = await fetch(`${API_BASE_URL}/articles/${id}`, {
    headers: token ? { Authorization: `Bearer ${token}` } : {}
  })

  if (!res.ok) {
    throw new Error('文章不存在')
  }

  return await res.json()
}

// 获取文章评论
export const fetchComments = async (articleId: number): Promise<Comment[]> => {
  const res = await fetch(`${API_BASE_URL}/articles/${articleId}/comments`)
  
  if (res.ok) {
    return await res.json()
  }
  
  return []
}

// 提交评论
export const submitComment = async (articleId: number, content: string): Promise<void> => {
  const token = localStorage.getItem('token')
  const res = await fetch(`${API_BASE_URL}/articles/${articleId}/comments`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${token}`
    },
    body: JSON.stringify({ content })
  })

  if (!res.ok) {
    const err = await res.json()
    throw new Error(err.message || '评论失败')
  }
}

// 获取封面图片URL
export const getCoverUrl = (url?: string): string => {
  if (!url) return 'https://picsum.photos/800/400?random=default'
  if (/^https?:/.test(url)) return url
  return `${API_BASE_URL}${url}`
}

// 处理图片加载错误
export const onImgError = (e: Event): void => {
  const target = e.target as HTMLImageElement
  if (target) target.src = 'https://picsum.photos/800/400?random=default'
} 